package com.springBoot.springBootSysCore.modules.shiro;

import com.springBoot.springBootSysCore.common.config.Global;
import org.apache.shiro.web.filter.authc.AnonymousFilter;
import org.apache.shiro.web.filter.mgt.FilterChainManager;
import org.apache.shiro.web.filter.mgt.NamedFilterList;
import org.apache.shiro.web.filter.mgt.PathMatchingFilterChainResolver;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import java.util.ArrayList;
import java.util.List;

/**
 * 默认情况下如使用ShiroFilterFactoryBean创建shiroFilter时，默认使用PathMatchingFilterChainResolver进行解析，
 * 而它默认是根据当前请求的URL获取相应的拦截器链，使用Ant模式进行URL匹配；
 * 默认使用DefaultFilterChainManager进行拦截器链的管理。
 * @author timo
 */
public class CustomPathMatchingFilterChainResolver extends PathMatchingFilterChainResolver {
    
    public FilterChain getChain(ServletRequest request, ServletResponse response, FilterChain originalChain) {
    	FilterChainManager filterChainManager = getFilterChainManager();//1、首先获取拦截器链管理器
    	if (!filterChainManager.hasChains()) {
            return null;
        }
        String requestURI = getPathWithinApplication(request);//2、接着获取当前请求的URL（不带上下文）

        if((Global.getAdminPath()+"/pageSkip/jumpPage").equals(requestURI)){
            String pageUrl = request.getParameter("pageUrl");
            requestURI=requestURI+"?pageUrl="+pageUrl;
        }

        List<String> chainNames = new ArrayList<String>();

//        for (String pathPattern : filterChainManager.getChainNames()) {
//            // If the path does match, then pass on to the subclass implementation for specific checks:
//            if (pathMatches(pathPattern, requestURI)) {
//                chainNames.add(pathPattern);
//            }
//        }
        for (String pathPattern : filterChainManager.getChainNames()) {//3、循环拦截器管理器中的拦截器定义（拦截器链的名字就是URL模式）
        	NamedFilterList fil = filterChainManager.getChain(pathPattern);
        	if (pathMatches(pathPattern, requestURI)) { //4、如当前URL匹配拦截器名字（URL模式）
            	Filter a =fil.get(0);
        		if(AnonymousFilter.class.getName().equals(a.getClass().getName())){
            		chainNames.clear();
            		chainNames.add(pathPattern);
            		break;
            	}
            	chainNames.add(pathPattern);
            }
        }
        if(chainNames.size() == 0) {
            return null;
        }
        FilterChain f= ((CustomDefaultFilterChainManager)filterChainManager).proxy(originalChain, chainNames);
        return f;//5、返回该URL模式定义的拦截器链
    }
}
